package cn.edu.zime.tjh.iotapp;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private EditText etUsername, etPassword;
    private Button btnLogin;
    private TextView tvMessage;

    private final OkHttpClient client = new OkHttpClient();
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 初始化视图
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvMessage = findViewById(R.id.tvMessage);
        // 登录按钮点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();

                if (username.isEmpty() || password.isEmpty()) {
                    tvMessage.setText("用户名和密码不能为空");
                    tvMessage.setVisibility(View.VISIBLE);
                } else {
                    // 发起登录请求
                    login(username, password);
                }
            }
        });
    }

    private void login(String username, String password) {
        // 创建 JSON 请求体
        JSONObject json = new JSONObject();
        try {
            json.put("name", username);
            json.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(json.toString(), JSON);

        // 创建请求对象
        Request request = new Request.Builder()
                .url("http://192.168.1.103:8080/user/login")
                .post(requestBody)
                .build();

        // 发起异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvMessage.setText("网络请求失败，请检查网络连接");
                        tvMessage.setVisibility(View.VISIBLE);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 请求成功
                    String responseBody = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                // 解析服务器返回的 JSON 数据
                                JSONObject jsonResponse = new JSONObject(responseBody);
                                boolean success = jsonResponse.getBoolean("success");
                                String message = jsonResponse.getString("message");

                                if (success) {
                                    // 登录成功
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    // 登录失败
                                    tvMessage.setText(message);
                                    tvMessage.setVisibility(View.VISIBLE);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                tvMessage.setText("服务器返回数据格式错误");
                                tvMessage.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                } else {
                    // 请求失败
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvMessage.setText("登录失败，请重试");
                            tvMessage.setVisibility(View.VISIBLE);
                        }
                    });
                }
            }
        });
    }

    public void back(View V){
        finish();
    }
}
